import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.gearman.common.GearmanNIOJobServerConnection;
import org.gearman.worker.GearmanFunction;
import org.gearman.worker.GearmanWorker;

public class GearBgWorker {
	private static Logger LOGGER = Logger.getLogger(GearBgWorker.class); ; 
	GearmanNIOJobServerConnection conn;		
    List<Class<GearmanFunction>> functions;	    
    
    
	@SuppressWarnings(value = "unchecked")
	public GearBgWorker(String host, int port, List<Class<GearmanFunction>> funs) {
		 conn = new GearmanNIOJobServerConnection(host, port);
	        functions = new ArrayList<Class<GearmanFunction>>();
	        functions.addAll(funs);		
	}
	
	public void start() {
        GearmanWorker worker = new MyGearmanWorkerImpl();
        worker.addServer(conn);
        
        for (Class<GearmanFunction> fun : functions) {
            worker.registerFunction(fun);
            System.out.println("Register function: " + fun);
        }
        worker.work();
    }
	
	@SuppressWarnings(value = "unchecked")
    public static void main(String[] args) {    
        List<Class<GearmanFunction>> functions =
                new ArrayList<Class<GearmanFunction>>();
        
        String host = GearConstants.GEARSERVER_HOST; 
        int port = GearConstants.GEARSERVER_PORT;
                
        for (String arg : args) {
            if (arg.startsWith("-h")) {
                host = arg.substring(2);
            } else if (arg.startsWith("-p")) {
                port = Integer.parseInt(arg.substring(2));
            }            
        }
        
        GearConstants.FunctionName funcs[] = GearConstants.FunctionName.values();
        
    	for (GearConstants.FunctionName f : funcs) {
            
    		try {
    			Class c = Class.forName(f.getName());
	            if (!GearmanFunction.class.isAssignableFrom(c)) {	            	
	                System.out.println(f.getName() + " is not an instance of " + GearmanFunction.class.getCanonicalName());
	                return;
	            }
	            functions.add((Class<GearmanFunction>)c);
            
        	} catch (ClassNotFoundException cfne) {
                System.out.println("Can not find function " + f.getName() + " on class path");
                return;
            }
    	}
        
        new GearBgWorker(host, port,functions).start();
    }
	
}
